package com.hefan.api.controller.oms;

import com.alibaba.dubbo.config.annotation.Reference;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.common.meta.UserTypeEnum;
import com.cat.tiger.util.CollectionUtils;
import com.cat.tiger.util.Fraction;
import com.cat.tiger.util.GlobalConstants;
import com.google.common.collect.Maps;
import com.hefan.api.service.UserLocalService;
import com.hefan.api.service.oms.ExChangeLocalService;
import com.hefan.api.service.oms.ExchangeRuleLocalService;
import com.hefan.common.util.HttpUtils;
import com.hefan.common.util.MapUtils;
import com.hefan.common.util.NumberUtils;
import com.hefan.oms.bean.ExchangeDetail;
import com.hefan.oms.itf.CurrencyExchangeService;
import com.hefan.user.bean.WebUser;
import com.hefan.user.bean.WebUserIdentity;
import com.hefan.user.itf.UserIdentityService;
import com.hefan.user.itf.WebUserAccountService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import com.hefan.common.util.NumberUtils;

/**
 * Created by hbchen on 2016/10/10.
 */
@Controller
@RequestMapping("v1/currencyExchange")
public class CurrencyExchangeController {

    @Resource
    ExChangeLocalService exChangeLocalService;
    @Resource
    ExchangeRuleLocalService exchangeRuleLocalService;
    @Reference
    UserIdentityService userIdentityService;
    @Reference
    CurrencyExchangeService currencyExchangeService;
    @Resource
    private UserLocalService userLocalService;
    @Reference
    private WebUserAccountService webUserAccountService;

    public static Logger logger = LoggerFactory.getLogger(CurrencyExchangeController.class);

    @RequestMapping("/doMealTicketExchange")
    @ResponseBody
    public ResultBean doMealTicketExchange(HttpServletRequest request){
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS.get_code(), ResultCode.SUCCESS.getMsg());
        Map m  = HttpUtils.initParam(request,Map.class);
        String userId = "";
        Integer fanpiaoNum = 0;
        Integer hefanNum = 0;
        if(m!=null) {
             userId = MapUtils.getStrValue(m,"userId","");
             fanpiaoNum = MapUtils.getIntValue(m,"fanpiaoNum",0);
             hefanNum = MapUtils.getIntValue(m,"hefanNum",0);
        }else{
            return new ResultBean(ResultCode.ParamException.get_code(), "参数验证错误");
        }
        if (StringUtils.isBlank(userId))
            return new ResultBean(ResultCode.ParamException.get_code(), "参数验证错误");
        if (null == fanpiaoNum || fanpiaoNum <= 0)
            return new ResultBean(ResultCode.ParamException.get_code(), "兑换饭票数不能为0");
        if (null == hefanNum || hefanNum <= 0)
            return new ResultBean(ResultCode.ParamException.get_code(), "兑换需要的盒饭数不能为0");
        if (fanpiaoNum % 100 != 0)
            return new ResultBean(ResultCode.ParamException.get_code(), "饭票数应为100的倍数");
        try {
            WebUser webUser = userLocalService.findUserInfoFromCache(userId);
            if(webUser == null) {
                return new ResultBean(ResultCode.ParamException.get_code(), "用户信息不存在");
            }
            Integer availableTickets = 0;
            WebUserIdentity webUserIdentity = null;
            if(UserTypeEnum.isAnchor(webUser.getUserType())) {//主播
                availableTickets = exChangeLocalService.selectAvailableTickets(userId);
                webUserIdentity = userIdentityService.getUserIndentityInfo(userId);
                if (webUserIdentity==null){
                    return new ResultBean(ResultCode.UNSUCCESS.get_code(),"分成比例错误");
                }
            } else {
                availableTickets = Long.valueOf(webUserAccountService.getBaseUserIncome(userId)).intValue();
            }
            ExchangeDetail item = new ExchangeDetail();
            item.setTransactionNumber(createSrl());
            item.setUserId(userId);
            item.setExchangeTime(new Date());
            item.setFanpiaoNum(fanpiaoNum);// 兑换的饭票数
            item.setHefanNum(hefanNum);// 兑换需要的盒饭数
            item.setBeforeHefanNum(availableTickets);// 兑换前盒饭数
            if(null != webUserIdentity)
                item.setPid(webUserIdentity.getPid());
            else
                item.setPid(0);
            resultBean = exChangeLocalService.doMealTicketExchange(item,webUser,webUserIdentity);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return new ResultBean(ResultCode.UNSUCCESS.get_code(), "兑换失败");
        }
        return resultBean;
    }

    private String createSrl() {
        String tmpSrl = "" + (int) ((Math.random() * 9 + 1) * 100000);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(new Date()) + tmpSrl;
    }

    private Map<String, Object> getExchangeRuleForHeFanOrFanPiao(Map exRuleMap,Integer radio){
        Map<String, Object> resultMap = Maps.newHashMap();
        Integer exchangeRatioOld =  (Integer)exRuleMap.get("exchangeRatio"); //1
        Integer beExchangeRatioOld =  (Integer)exRuleMap.get("beExchangeRatio");//10
        Fraction fraction = new Fraction(exchangeRatioOld,beExchangeRatioOld);
        Fraction fraction1 = fraction.division(radio);
        Fraction fraction2 = fraction1.division1(100);
        resultMap.put("exchangeRatio", fraction2.getNumerator());
        resultMap.put("beExchangeRatio", fraction2.getDenominator());
        return resultMap;
    }
}
